﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.Entities;
using MovieRental.DataInterfaces;
using MovieRental.GeneralDataExceptions;
using MovieRental.EfRepositoryLibrary.Mappers;

namespace MovieRental.EfRepositoryLibrary
{
    public class EfCustomerRepository : EfRepository<CustomerInfo, Guid, Customer, Customer>, ICustomerRepository
    {
        public EfCustomerRepository(string connectionString)
            : base(connectionString)
        {
            _mapper = new CustomerMapper();
        }

        public override void Delete(Guid id)
        {
            using (var context = CreateContext())
            {
                foreach (var cart in context.LoanCarts.Where(x => x.CustomerId == id))
                    cart.CustomerId = null;
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Can't delete object from the db.", ex);
                }  
            }
            base.Delete(id);
        }


        public bool ContainsCustomer(Guid id)
        {
            using (var context = CreateContext())
            {
                try
                {
                    return context.Customers.Any(x => x.Id == id);
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Connection error.", ex);
                }
            }
        }
    }
}
